package com.tangdi.production.mpaychl.controller.req;

import com.acq.sdk.Constants;
import com.tangdi.production.mpaychl.controller.BaseController;
import com.tangdi.production.mpaychl.dao.AllpayReqContentMapper;
import com.tangdi.production.mpaychl.model.AllpayReqContent;
import com.tangdi.production.mpaychl.service.impl.wxpay.utils.HttpUtil;
import com.tangdi.production.mpaychl.service.impl.wxpay.utils.PayCommonUtil;
import com.tangdi.production.mpaychl.service.impl.wxpay.utils.PayConfig;
import com.tangdi.production.mpaychl.service.impl.wxpay.utils.XMLUtil;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.util.ObjectUtil;
import com.tangdi.production.mpbase.util.SHAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

@Controller
public class WeixinController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(WeixinController.class);

    @Autowired
    private AllpayReqContentMapper reqContentMapper;

    @RequestMapping("weixinpay")
    public ModelAndView weixinPay(HttpServletRequest request, HttpServletResponse response){

        logger.info("进入WX-H5处理接口");

        Map<String, String> params = getRequestParams(request);
        logger.info("weixinpay,参数:{}", params);

        String prdordno = "" + params.get("prdordno");
        String payAmt = ObjectUtil.getString(params.get("payAmt"));
        String orderDesc = "" + params.get("orderDesc");

        try {
            // 账号信息
            // appid
            String appid = PayConfig.APP_ID;
            // 商业号
            String mch_id = PayConfig.MCH_ID;
            // key
            String key = PayConfig.API_KEY;

            String currTime = PayCommonUtil.getCurrTime();
            String strTime = currTime.substring(8, currTime.length());
            String strRandom = PayCommonUtil.buildRandom(4) + "";
            String nonce_str = strTime + strRandom;

            // 价格 注意：价格的单位是分
            String order_price = payAmt;

            // 自己网站上的订单号
            String out_trade_no = prdordno;
            // 获取发起电脑 ip
            String spbill_create_ip = Constants.LOCAL_HOST_IP;

            // 回调接口
            String notify_url = PayConfig.NOTIFY_URL_H5_DOMAIN;

            String trade_type = "MWEB";

            // 设置package订单参数
            SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
            packageParams.put("appid", appid);
            packageParams.put("mch_id", mch_id);

            // 生成签名的时候需要你自己设置随机字符串
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("sign_type", "MD5");
            packageParams.put("body", PayConfig.BODY);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("total_fee", order_price);
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", notify_url);
            packageParams.put("trade_type", trade_type);
            packageParams.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"www.newiba.com\",\"wap_name\": \"商品交易\"}}");
            String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
            packageParams.put("sign", sign);
            String requestXML = PayCommonUtil.getRequestXml(packageParams);

            // 请求微信支付
            logger.info("请求参数:{}", requestXML);
            String resXml = HttpUtil.postData(PayConfig.UFDODER_URL, requestXML);
            logger.info("返回参数:{}", resXml);
            Map map = XMLUtil.doXMLParse(resXml);
//            String urlCode = (String) map.get("code_url");

            if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {

                // 确认支付过后跳的地址,页面跳转同步通知页面路径,需要经过urlencode处理
                String urlString = URLEncoder.encode(String.valueOf(params.get("frontUrl")), "GBK");
                String mweb_url = map.get("mweb_url")+"&redirect_url="+urlString;

                System.out.println(mweb_url);

                AllpayReqContent record = new AllpayReqContent();
                record.setHashCode(SHAUtil.SHA(mweb_url));
                record.setOrdNo(prdordno);
                record.setReqContent(mweb_url);
                record.setCreDttm(new Date());
                reqContentMapper.insertSelective(record);

                Map<String,Object> backMap = new HashMap<>();
                backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
                backMap.put("contentType", MsgCT.DATA_TYPE_HTML);
                backMap.put("busContent", Constants.REQ_ADDRESS_DOMAIN + "/pay/redirect/" + SHAUtil.SHA(mweb_url) + ".ac");

                ModelAndView mav =  new ModelAndView("/weixin/weixinpay");
                mav.addObject("redirect_url", backMap.get("busContent"));

                return mav;
            } else {
                Map<String,Object> backMap = new HashMap<>();
                backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
                backMap.put("contentType", MsgCT.DATA_TYPE_HTML);
                backMap.put("busContent", "");
            }
        } catch (Exception e) {
            logger.error("渠道WX-H5调用异常:{}", e.getMessage(), e);
            Map<String,Object> backMap = new HashMap<>();
            backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
            backMap.put("msg", "渠道WX-H5调用异常:" + e.getMessage());
        }

        return null;
    }

}
